/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datas;

import beans.customer;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.validation.Validator;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;
import org.xml.sax.SAXException;

/**
 *
 * @author havn
 */
public class XMLDom {

    public List read(String keyword) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new File("D:\\Customers.xml"));
            List list = new ArrayList<customer>();

            DocumentTraversal traversal = (DocumentTraversal) doc;
            NodeList nl = doc.getElementsByTagName("customer");
            for (int i = 0; i < nl.getLength(); i++) {
                NodeList Citynl = doc.getElementsByTagName("city");
                Element city = (Element) Citynl.item(i);
                if (!keyword.equals("")) {
                    if (city.getChildNodes().item(0).getNodeValue().equals(keyword)) {
                        list.add(LoadNode(doc, i));
                    }
                } else {
                    list.add(LoadNode(doc,i));
                }

            }
            return list;
        } catch (SAXException ex) {
            Logger.getLogger(XMLDom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLDom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLDom.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private customer LoadNode(Document doc, int i) {
        //id
        customer cust = new customer();
        NodeList IDnl = doc.getElementsByTagName("id");
        Element ele = (Element) IDnl.item(i);
        cust.setId(ele.getChildNodes().item(0).getNodeValue());
        //name
        NodeList Namenl = doc.getElementsByTagName("name");
        ele = (Element) Namenl.item(i);
        cust.setName(ele.getChildNodes().item(0).getNodeValue());
        //address
        NodeList Addressnl = doc.getElementsByTagName("address");
        ele = (Element) Addressnl.item(i);
        cust.setAddress(ele.getChildNodes().item(0).getNodeValue());
        //city
        NodeList Citynl = doc.getElementsByTagName("city");
        ele = (Element) Citynl.item(i);
        cust.setCity(ele.getChildNodes().item(0).getNodeValue());
        return cust;
    }

    private void traverseLevel(TreeWalker walker, String indent) {
        Node parend = walker.getCurrentNode();
        System.out.println(indent + "- " + ((Element) parend).getTagName());

        for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
            traverseLevel(walker, indent + '\t');
        }
        walker.setCurrentNode(parend);
    }

    public String validate() {
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse("D:\\Customers.xml");
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaFile = new StreamSource("D:\\SchemaCustomer.xsd");
            Schema schema = factory.newSchema(schemaFile);
            Validator valid = schema.newValidator();
            valid.validate(new DOMSource(doc));
            return "Document is valid";
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }

    public void write(Vector<customer> list) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();
            Element root = doc.createElement("customers");
            for (int i = 0; i < list.size(); i++) {
                customer cus = list.elementAt(i);
                Element customer = doc.createElement("customer");

                //id
                Element id = doc.createElement("id");
                id.setTextContent(cus.getId());
                customer.appendChild(id);
                //name
                Element name = doc.createElement("name");
                name.setTextContent(cus.getName());
                customer.appendChild(name);

                //title
                Element title = doc.createElement("title");
                title.setTextContent(cus.getTitle());
                customer.appendChild(title);
                //address
                Element address = doc.createElement("address");
                address.setTextContent(cus.getAddress());
                customer.appendChild(address);
                //city
                Element city = doc.createElement("city");
                city.setTextContent(cus.getCity());
                customer.appendChild(city);
                root.appendChild(customer);
            }
            doc.appendChild(root);
            TransformerFactory trans = TransformerFactory.newInstance();
            Transformer former = trans.newTransformer();
            former.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            former.setOutputProperty(OutputKeys.INDENT, "yes");
            //
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("D:\\Customers.xml"));
            former.transform(source, result);
        } catch (Exception ex) {
        }

    }

    public void print() {
    }
}
